import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Api from '@/utils/tool/api'         // url

// 创建axios实例
const service = axios.create({
  baseURL: Api.requestURL,  
  // withCredentials: true, // 跨域请求时发送cookie
  // timeout: 5000 // request timeout
})
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截器
service.interceptors.request.use(
  config => { 
    // console.log('请求拦截config',config);
    if (getToken()) { 
      config.headers['satoken'] = getToken()
    }
    return config
  },
  error => {
    // 处理请求错误
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use( 
  response => {
    const res = response.data
    // console.log('响应拦截res',res);
    if (res.code !== 200) {
      // 如果501表示token过期，跳转至父系统登录页
      if (res.code==501) {
        setTimeout(()=>{
          // router.push({ path: '/login' })
          localStorage.removeItem('userInfo')
          sessionStorage.removeItem('userInfo')
          window.location.href = 'https://matefarm.net/agricultural-unified-login/#/login'
        },0)
      }else{
        Message({
          message: res.msg || '出现未知错误，请刷新后重试！',
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(new Error(res.message || res.msg))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
